package com.CST.service.impl.cb;

import com.CST.common.api.Response;
import com.CST.dto.cb.DateDTO;
import com.CST.entity.cb.AllocationCoefficient;
import com.CST.mapper.cst.cb.AllocationCoefficientMapper;
import com.CST.service.cb.IAllocationCoefficientService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AllocationCoefficientServiceImpl  implements IAllocationCoefficientService {
    
    @Autowired
    private AllocationCoefficientMapper allocationCoefficientMapper;
    
    @Override
    public Response insertCoefficient(DateDTO dateDTO) {
        // 职工人数
        List<AllocationCoefficient> employee = allocationCoefficientMapper.listCoefficientWithEmployee(dateDTO);
        // 实际床日
        List<AllocationCoefficient> ward = allocationCoefficientMapper.listCoefficientWithWard(dateDTO);
        // 房屋面积
        List<AllocationCoefficient> area = allocationCoefficientMapper.listCoefficientWithArea(dateDTO);
        // 门诊人次
        List<AllocationCoefficient> outPatient = allocationCoefficientMapper.listCoefficientWithOutPatient(dateDTO);
        // 出院人次
        List<AllocationCoefficient> leave = allocationCoefficientMapper.listCoefficientWithLeave(dateDTO);
        
        // 先删除当前年月的系数
        allocationCoefficientMapper.deleteByDate(dateDTO);
        
        List<AllocationCoefficient> coefficientList = new ArrayList<>();
        coefficientList.addAll(employee);
        coefficientList.addAll(ward);
        coefficientList.addAll(area);
        coefficientList.addAll(outPatient);
        coefficientList.addAll(leave);
        // 批量插入
        Integer year = dateDTO.getYear();
        int total1 = coefficientList.size();//为防止插入字符超过最大数,分批插入
        int fromIndex1 = 0;
        List<AllocationCoefficient> insertList1 = new ArrayList<>();
        for (int i = 0; i < coefficientList.size(); i++) {
            AllocationCoefficient coefficient = coefficientList.get(i);
            fromIndex1++;
            insertList1.add(coefficient);
            if (fromIndex1 % 20 == 0 && fromIndex1 <= total1) {
                allocationCoefficientMapper.insertByYear(insertList1, year);
                insertList1 = new ArrayList<>();
            }
        }
        if (CollectionUtils.isNotEmpty(insertList1)) {
            allocationCoefficientMapper.insertByYear(insertList1, year);
        }
        return Response.success("采集成功");
    }
}
